import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config} from '../../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
declare var $: any;
@Component({
  selector: 'sa-rail-bindCar-page',
  templateUrl: './rail-bindCar-page.component.html',
})
export class RailBindCarPageComponent implements OnInit {
	pageType:string = '';
	roleId:string = '5c6d0be763c79917246ba320'; //角色id
	curPage:number = 0;//缓存页码
	menuIds:any = [];
	companyCar:any = [];
	searchKey:string = ''; //树形图查询关键字
	markerId:string='';//围栏id
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.roleId = '5c6d0be763c79917246ba320';
			this.pageType = queryParams.pageType;
			this.curPage = queryParams.nowPage;
			this.markerId = queryParams.markerId;
		});
	}
	//tree search功能
	table_search(){
		if(!this.searchKey){return;}
		$("#tree").jstree(true).search(this.searchKey);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			this.jsonApiService.message('没有对应数据');
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#tree_content'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#tree_content').height() * 0.3});
			}
		})
	}
	//展开tree
	allOpen(){
		$('#tree').jstree(true).open_all();
	}
	//折叠tree
	allClose(){
		$('#tree').jstree(true).close_all();
	}
	//初始化拉取数据(下拉列表)
	initdata() {
		var that = this;
		$('#tree').jstree({
				"core": {
					'data': function(obj, callback) {       
						var jsonstr = "[]";       
						var jsonarray = eval('(' + jsonstr + ')');
						var url = 'mapmarker/carTreeSelectForMapMarker.html';
						$.ajax({        
							type: "GET",
					        url: config.BaseURL + url + "?markerId=" + that.markerId,
					        dataType: "json",
							xhrFields: {
								withCredentials: true
							},
					        success: function(data) {
								var result = data.data;
								this.companyCar = result;
								if(result[0].remark === 'company' || result[0].remark === 'car'){
									for(let i = 0; i < result.length; i++){
										if(result[i].state.selected && result[i].remark === 'company'){
											this.getChildren(result[i],i);//处理没有子级的选项状态
										}
									}
								}
								jsonarray = this.companyCar;  
								callback.call(this, jsonarray); 
							}.bind(this)         
						});      
				}.bind(this),
				"themes": {
					"responsive": true
				},
				"multiple": true,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"checkbox": {
				"keep_selected_style": false,
				"three_state": true, //父子级别级联选择
				"cascade": "down"
			},
			"plugins": ["checkbox","search"]
		});
	}
	getChildren(val,i){
		for(let j = 0; j < this.companyCar.length; j++){
			if(val.id === this.companyCar[j].parent){
				this.companyCar[i].state.selected = false;
				break;
			}
		}
	}
	getParents(treeObj, nodeObj){
		var parentId = treeObj.get_parent(nodeObj);
		if(nodeObj.original.remark === 'company'){
				this.menuIds.push(nodeObj.id);
			}
        if (parentId != "#") {
        	if(this.menuIds)
            this.menuIds.push(parentId);
            this.getParents(treeObj, treeObj.get_node(parentId));
        }
	}
	//权限数据保存
	saveDate(){
		this.menuIds = [];
		var tree = $('#tree').jstree();
        var selectedIds = tree.get_checked();   //获取所有选中节点id
       
        var selected = tree.get_checked(true);  //获取所有选中节点数据
        for (var i = 0; i < selected.length; i++) {
        	this.getParents(tree, selected[i]);
        }
		let companyIds = Array.from(new Set(this.menuIds)).join(',');//去重+类型转化
        let temCompanyArr:any = companyIds.split(',');
        let temDeviceIdsArr:any = [];
        for(var j = 0; j < selectedIds.length; j++){
        	for(var k = 0; k < temCompanyArr.length; k++){
        		if(selectedIds[j] !== temCompanyArr[k] && !temDeviceIdsArr.includes(selectedIds[j]) && !temCompanyArr.includes(selectedIds[j])){
        			temDeviceIdsArr.push(selectedIds[j]);//提出父级公司id,筛选出子级车辆设备id
        		}
        	}
        }
        let deviceIds = temDeviceIdsArr.join(',');
        if(!deviceIds){
        	this.jsonApiService.message('至少选择一条车辆数据');
        	return;
        } 
        let reqdata = "carId="+deviceIds+"&mapMarkerId="+this.markerId;
	 	this.jsonApiService.http('mapmarker/addCarMapMarkerConfig.html',reqdata).subscribe(data=> {
	 		this.jsonApiService.message(data.message);
	 		if(data.success){
	 			this.goBack();
	 		}
		})
	}
	//返回
	goBack(){
		if(this.pageType=='loadBind'){
			this.router.navigate(['/data-statistics/rail/rail-loadBind'],{ queryParams: {nowPage:this.curPage}});
		}
		if(this.pageType=='unloadBind'){
			this.router.navigate(['/data-statistics/rail/rail-unloadBind'],{ queryParams: {nowPage:this.curPage}});
		}
	}
	ngOnInit() {
		System.import('assets/js/jstree/jstree.min.js').then(()=>{
			this.initdata();
		})
	}

}
